package com.example.demo.thread.lock.lockInterruptibly;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lockInterruptibly()
 * 当通过这个方法去获取锁时，如果线程正在等待获取锁，则这个线程能够响应中断，即中断线程的等待状态。
 * 也就使说，当两个线程同时通过lock.lockInterruptibly()想获取某个锁时，假若此时线程A获取到了锁，而线程B只有在等待，
 * 那么对线程B调用threadB.interrupt()方法能够中断线程B的等待过程。
 *
 * @author luowj12
 * @since 2021/5/13 15:59
 */
public class LockInterruptibly01 implements Runnable{

    private static Lock lock = new ReentrantLock();

    @Override
    public void run(){
        try{
            System.out.println(Thread.currentThread().getName() + "trying to get lock");
            lock.lockInterruptibly();

            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName() + " finished");
        } catch (InterruptedException e){
            System.out.println(Thread.currentThread().getName() + " interrupted");
        }
        finally{
            lock.unlock();
            System.out.println("now lock is avalibale");
        }
    }




}
